package com.gitee.shop.controller;

import com.gitee.shop.domain.Cart;
import com.gitee.shop.domain.CartItem;
import com.gitee.shop.domain.Item;
import com.gitee.shop.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/cart")
public class CartController {

    //注入service
    @Autowired
    private ItemService itemService;

    //添加购物车
    @RequestMapping("/add")
    public String add(int count , int id, HttpServletRequest request){
        Item item = itemService.selectByPrimaryKey(id);

        //创建购物车
        CartItem cartItem = new CartItem(item, count);

        //将购物项加入购物车
        //从session中取购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart== null){   // 如果没有取出，说明还没有购物车
            //创建购物车
            cart = new Cart();
            //添加购物项
            cart.addCartItem(cartItem);
            //将购物项添加至session
            request.getSession().setAttribute("cart", cart);
        }else{
            //如果有 直接添加
            cart.addCartItem(cartItem);
        }
        return "cart";
    }

    //清空购物车
    @RequestMapping("/clear")
    public String clear(HttpSession session){
        Cart cart = (Cart) session.getAttribute("cart");
        cart.clear();
        session.removeAttribute("cart");
        return "cart";
    }
}
